from typing import Optional

from skywalking import Component, Layer, config
from skywalking.trace import tags
from skywalking.trace.carrier import Carrier
from skywalking.trace.context import get_context
from skywalking.trace.span import NoopSpan
from skywalking.trace.tags import Tag


def install():
    import quart
    
    _full_dispatch_request = quart.Quart.full_dispatch_request
    _handle_user_exception = quart.Quart.handle_user_exception
    _handle_exception = quart.Quart.handle_exception

    def params_tostring(params):
        return "\n".join([k + '=[' + ",".join(params.getlist(k)) + ']' for k, _ in params.items()])

    def __get_client_ip(request):
        '''
        获取客户端IP
        '''
        keys = ["x-forwarded-for", 'x-real-ip']
        for key, value in request.headers.items():
            if key.lower().strip() in keys:
                return value
        return request.remote_addr

    async def _sw_full_dispatch_request(this: quart.Quart, request_context: Optional[quart.app.RequestContext] = None):
        req = quart.request
        context = get_context()
        carrier = Carrier()

        remote_add = __get_client_ip(req)
        remote_port = ""
        if "REMOTE_PORT" not in req.headers:
            remote_port = ""

        for item in carrier:
            if item.key.capitalize() in req.headers:
                item.val = req.headers[item.key.capitalize()]
        with context.new_entry_span(op=req.path, carrier=carrier) as span:
            span.layer = Layer.Http
            span.component = Component.Flask
            span.peer = '%s:%s' % (
                remote_add,
                remote_port
            )
            span.tag(Tag(key=tags.HttpMethod, val=req.method))
            span.tag(Tag(key=tags.HttpUrl, val=req.url.split("?")[0]))
            values = await req.values
            if config.flask_collect_http_params and values:
                span.tag(Tag(key=tags.HttpParams,
                            val=params_tostring(values)[0:config.http_params_length_threshold]))

            resp = await _full_dispatch_request(this, request_context=request_context)

            if resp.status_code >= 400:
                span.error_occurred = True

            span.tag(Tag(key=tags.HttpStatus,
                        val=resp.status_code, overridable=True))
            return resp

    def _sw_handle_user_exception(this: quart.Quart, e):
        if e is not None:
            entry_span = get_context().active_span()
            if entry_span is not None and type(entry_span) is not NoopSpan:
                entry_span.raised()

        return _handle_user_exception(this, e)

    async def _sw_handle_exception(this: quart.Quart, e):
        if e is not None:
            entry_span = get_context().active_span()
            if entry_span is not None and type(entry_span) is not NoopSpan:
                entry_span.raised()

        return await _handle_exception(this, e)

    quart.Quart.full_dispatch_request = _sw_full_dispatch_request
    quart.Quart.handle_user_exception = _sw_handle_user_exception
    quart.Quart.handle_exception = _sw_handle_exception
